<template>
  <div class="meters-monitoring">
    <div class="page-header">
      <h2>水电表监控</h2>
      <Space>
        <Button @click="refreshMeters">
          <IconifyIcon icon="ant-design:reload-outlined" />
          刷新数据
        </Button>
        <Button type="primary" @click="showAddMeterModal = true">
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加表计
        </Button>
      </Space>
    </div>

    <!-- 表计统计 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="表计总数"
          :value="statistics.totalMeters"
          :change="statistics.totalChange"
          icon="ant-design:thunderbolt-outlined"
          color="#1890ff"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="在线表计"
          :value="statistics.onlineMeters"
          :change="statistics.onlineChange"
          icon="ant-design:check-circle-outlined"
          color="#52c41a"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="异常表计"
          :value="statistics.abnormalMeters"
          :change="statistics.abnormalChange"
          icon="ant-design:warning-outlined"
          color="#faad14"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="今日用量"
          :value="statistics.todayUsage"
          :change="statistics.usageChange"
          icon="ant-design:dashboard-outlined"
          color="#722ed1"
        />
      </Col>
    </Row>

    <!-- 实时监控面板 -->
    <Row :gutter="16" class="monitoring-panel">
      <Col :span="12">
        <Card title="用水量监控" class="water-monitoring">
          <div class="monitoring-content">
            <div class="usage-summary">
              <div class="usage-item">
                <span class="usage-label">总用水量</span>
                <span class="usage-value">{{ waterSummary.total }} m³</span>
              </div>
              <div class="usage-item">
                <span class="usage-label">今日用水</span>
                <span class="usage-value">{{ waterSummary.today }} m³</span>
              </div>
              <div class="usage-item">
                <span class="usage-label">本月用水</span>
                <span class="usage-value">{{ waterSummary.month }} m³</span>
              </div>
            </div>
            <div class="usage-chart">
              <div class="chart-placeholder">
                <IconifyIcon
                  icon="ant-design:line-chart-outlined"
                  class="chart-icon"
                />
                <p>用水量趋势图</p>
              </div>
            </div>
          </div>
        </Card>
      </Col>
      <Col :span="12">
        <Card title="用电量监控" class="electric-monitoring">
          <div class="monitoring-content">
            <div class="usage-summary">
              <div class="usage-item">
                <span class="usage-label">总用电量</span>
                <span class="usage-value">{{ electricSummary.total }} kWh</span>
              </div>
              <div class="usage-item">
                <span class="usage-label">今日用电</span>
                <span class="usage-value">{{ electricSummary.today }} kWh</span>
              </div>
              <div class="usage-item">
                <span class="usage-label">本月用电</span>
                <span class="usage-value">{{ electricSummary.month }} kWh</span>
              </div>
            </div>
            <div class="usage-chart">
              <div class="chart-placeholder">
                <IconifyIcon
                  icon="ant-design:line-chart-outlined"
                  class="chart-icon"
                />
                <p>用电量趋势图</p>
              </div>
            </div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 表计列表 -->
    <Card title="表计列表" class="meters-list-card">
      <div class="list-header">
        <Form layout="inline" :model="searchForm" class="search-form">
          <FormItem label="房间号">
            <Input
              v-model:value="searchForm.roomNumber"
              placeholder="请输入房间号"
              allow-clear
            />
          </FormItem>
          <FormItem label="表计类型">
            <Select
              v-model:value="searchForm.type"
              placeholder="请选择类型"
              allow-clear
              style="width: 120px"
            >
              <SelectOption value="water">水表</SelectOption>
              <SelectOption value="electric">电表</SelectOption>
            </Select>
          </FormItem>
          <FormItem label="表计状态">
            <Select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              allow-clear
              style="width: 120px"
            >
              <SelectOption value="online">在线</SelectOption>
              <SelectOption value="offline">离线</SelectOption>
              <SelectOption value="abnormal">异常</SelectOption>
            </Select>
          </FormItem>
          <FormItem label="楼层">
            <Select
              v-model:value="searchForm.floor"
              placeholder="请选择楼层"
              allow-clear
              style="width: 120px"
            >
              <SelectOption value="1">1楼</SelectOption>
              <SelectOption value="2">2楼</SelectOption>
              <SelectOption value="3">3楼</SelectOption>
              <SelectOption value="4">4楼</SelectOption>
              <SelectOption value="5">5楼</SelectOption>
            </Select>
          </FormItem>
          <FormItem>
            <Space>
              <Button type="primary" @click="handleSearch">
                <IconifyIcon icon="ant-design:search-outlined" />
                搜索
              </Button>
              <Button @click="handleReset">
                <IconifyIcon icon="ant-design:reload-outlined" />
                重置
              </Button>
            </Space>
          </FormItem>
        </Form>
      </div>
      <Table
        :columns="columns"
        :data-source="filteredMeters"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'roomNumber'">
            <div class="room-info">
              <div class="room-number">{{ record.roomNumber }}</div>
              <div class="room-type">{{ record.roomType }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'type'">
            <Tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'currentReading'">
            <div class="reading-info">
              <div class="reading-value">{{ record.currentReading }}</div>
              <div class="reading-unit">{{ getUnitText(record.type) }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'usage'">
            <div class="usage-info">
              <div class="usage-value">{{ record.usage }}</div>
              <div class="usage-unit">{{ getUnitText(record.type) }}</div>
            </div>
          </template>
          <template v-else-if="column.key === 'cost'">
            <div class="cost-info">
              <span class="cost-value">¥{{ record.cost }}</span>
            </div>
          </template>
          <template v-else-if="column.key === 'lastUpdate'">
            <div class="update-info">
              <span class="update-time">{{ record.lastUpdate }}</span>
              <span class="update-status" :class="record.status">
                {{ getUpdateStatusText(record.status) }}
              </span>
            </div>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewMeter(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="viewHistory(record)">
                历史
              </Button>
              <Button type="link" size="small" @click="calculateCost(record)">
                计费
              </Button>
              <Button type="link" size="small" @click="editMeter(record)">
                编辑
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 异常告警 -->
    <Card title="异常告警" class="alerts-card">
      <div class="alerts-list">
        <div
          v-for="alert in abnormalAlerts"
          :key="alert.id"
          class="alert-item"
          :class="alert.level"
        >
          <div class="alert-icon">
            <IconifyIcon :icon="getAlertIcon(alert.level)" />
          </div>
          <div class="alert-content">
            <div class="alert-title">{{ alert.title }}</div>
            <div class="alert-desc">{{ alert.description }}</div>
            <div class="alert-time">{{ alert.time }}</div>
          </div>
          <div class="alert-actions">
            <Button type="link" size="small" @click="handleAlert(alert)">
              处理
            </Button>
          </div>
        </div>
      </div>
    </Card>

    <!-- 添加表计弹窗 -->
    <Modal
      v-model:open="showAddMeterModal"
      title="添加表计"
      width="600px"
      @ok="handleSaveMeter"
      @cancel="handleCancelMeter"
    >
      <Form
        ref="meterFormRef"
        :model="meterForm"
        :rules="meterRules"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="房间号" name="roomNumber">
              <Input
                v-model:value="meterForm.roomNumber"
                placeholder="请输入房间号"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="表计类型" name="type">
              <Select
                v-model:value="meterForm.type"
                placeholder="请选择表计类型"
              >
                <SelectOption value="water">水表</SelectOption>
                <SelectOption value="electric">电表</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="表计型号" name="model">
              <Input
                v-model:value="meterForm.model"
                placeholder="请输入表计型号"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="表计厂商" name="manufacturer">
              <Input
                v-model:value="meterForm.manufacturer"
                placeholder="请输入表计厂商"
              />
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="初始读数" name="initialReading">
              <Input
                v-model:value="meterForm.initialReading"
                placeholder="请输入初始读数"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="表计状态" name="status">
              <Select
                v-model:value="meterForm.status"
                placeholder="请选择表计状态"
              >
                <SelectOption value="online">在线</SelectOption>
                <SelectOption value="offline">离线</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="IP地址" name="ipAddress">
              <Input
                v-model:value="meterForm.ipAddress"
                placeholder="请输入IP地址"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="端口号" name="port">
              <Input
                v-model:value="meterForm.port"
                placeholder="请输入端口号"
              />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="备注" name="remarks">
          <Textarea
            v-model:value="meterForm.remarks"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import StatisticsCard from '#/components/hotel/StatisticsCard.vue';
import {
  Button,
  Card,
  Col,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
} from 'ant-design-vue';

// 状态管理
const loading = ref(false);
const showAddMeterModal = ref(false);
const isEdit = ref(false);

// 表单引用
const meterFormRef = ref();

// 统计数据
const statistics = reactive({
  totalMeters: 32,
  totalChange: 2,
  onlineMeters: 30,
  onlineChange: 1,
  abnormalMeters: 2,
  abnormalChange: -1,
  todayUsage: 156.8,
  usageChange: 12.5,
});

// 用水量统计
const waterSummary = reactive({
  total: 1256.8,
  today: 45.2,
  month: 156.8,
});

// 用电量统计
const electricSummary = reactive({
  total: 3456.2,
  today: 128.5,
  month: 892.3,
});

// 搜索表单
const searchForm = reactive({
  roomNumber: '',
  type: '',
  status: '',
  floor: '',
});

// 表计表单
const meterForm = reactive({
  roomNumber: '',
  type: '',
  model: '',
  manufacturer: '',
  initialReading: '',
  status: 'online',
  ipAddress: '',
  port: '',
  remarks: '',
});

// 表单验证规则
const meterRules = {
  roomNumber: [{ required: true, message: '请输入房间号' }],
  type: [{ required: true, message: '请选择表计类型' }],
  model: [{ required: true, message: '请输入表计型号' }],
  initialReading: [{ required: true, message: '请输入初始读数' }],
  ipAddress: [{ required: true, message: '请输入IP地址' }],
};

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 表计数据
const meters = ref([
  {
    id: 1,
    roomNumber: '101',
    roomType: '标准间',
    type: 'water',
    status: 'online',
    currentReading: 1256.8,
    usage: 45.2,
    cost: 135.6,
    lastUpdate: '2024-01-19 15:30',
    model: 'WM-100',
    manufacturer: '威胜',
    ipAddress: '192.168.1.101',
  },
  {
    id: 2,
    roomNumber: '101',
    roomType: '标准间',
    type: 'electric',
    status: 'online',
    currentReading: 3456.2,
    usage: 128.5,
    cost: 385.5,
    lastUpdate: '2024-01-19 15:30',
    model: 'EM-200',
    manufacturer: '威胜',
    ipAddress: '192.168.1.102',
  },
  {
    id: 3,
    roomNumber: '102',
    roomType: '标准间',
    type: 'water',
    status: 'abnormal',
    currentReading: 892.3,
    usage: 0,
    cost: 0,
    lastUpdate: '2024-01-19 14:25',
    model: 'WM-100',
    manufacturer: '威胜',
    ipAddress: '192.168.1.103',
  },
  {
    id: 4,
    roomNumber: '102',
    roomType: '标准间',
    type: 'electric',
    status: 'online',
    currentReading: 2891.7,
    usage: 95.8,
    cost: 287.4,
    lastUpdate: '2024-01-19 15:30',
    model: 'EM-200',
    manufacturer: '威胜',
    ipAddress: '192.168.1.104',
  },
]);

// 异常告警数据
const abnormalAlerts = ref([
  {
    id: 1,
    level: 'critical',
    title: '水表读数异常',
    description: '102房间水表读数异常，可能存在漏水情况',
    time: '5分钟前',
  },
  {
    id: 2,
    level: 'warning',
    title: '电表离线',
    description: '205房间电表设备离线，请检查网络连接',
    time: '10分钟前',
  },
  {
    id: 3,
    level: 'info',
    title: '用量超常',
    description: '301房间今日用水量异常，请核实',
    time: '15分钟前',
  },
]);

// 表格列定义
const columns = [
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 120,
  },
  {
    title: '表计类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
  },
  {
    title: '表计状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '当前读数',
    dataIndex: 'currentReading',
    key: 'currentReading',
    width: 120,
  },
  {
    title: '今日用量',
    dataIndex: 'usage',
    key: 'usage',
    width: 120,
  },
  {
    title: '费用',
    dataIndex: 'cost',
    key: 'cost',
    width: 100,
  },
  {
    title: '最后更新',
    dataIndex: 'lastUpdate',
    key: 'lastUpdate',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 过滤后的表计数据
const filteredMeters = computed(() => {
  let result = meters.value;

  if (searchForm.roomNumber) {
    result = result.filter((item) =>
      item.roomNumber
        .toLowerCase()
        .includes(searchForm.roomNumber.toLowerCase()),
    );
  }

  if (searchForm.type) {
    result = result.filter((item) => item.type === searchForm.type);
  }

  if (searchForm.status) {
    result = result.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.floor) {
    result = result.filter((item) =>
      item.roomNumber.startsWith(searchForm.floor),
    );
  }

  return result;
});

// 类型相关函数
const getTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    water: 'blue',
    electric: 'green',
  };
  return colors[type] || 'default';
};

const getTypeText = (type: string) => {
  const texts: Record<string, string> = {
    water: '水表',
    electric: '电表',
  };
  return texts[type] || type;
};

// 状态相关函数
const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    online: 'green',
    offline: 'red',
    abnormal: 'orange',
  };
  return colors[status] || 'default';
};

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    online: '在线',
    offline: '离线',
    abnormal: '异常',
  };
  return texts[status] || status;
};

const getUpdateStatusText = (status: string) => {
  const texts: Record<string, string> = {
    online: '正常',
    offline: '离线',
    abnormal: '异常',
  };
  return texts[status] || status;
};

// 单位相关函数
const getUnitText = (type: string) => {
  const units: Record<string, string> = {
    water: 'm³',
    electric: 'kWh',
  };
  return units[type] || '';
};

// 告警相关函数
const getAlertIcon = (level: string) => {
  const icons: Record<string, string> = {
    critical: 'ant-design:close-circle-outlined',
    warning: 'ant-design:warning-outlined',
    info: 'ant-design:info-circle-outlined',
  };
  return icons[level] || 'ant-design:info-circle-outlined';
};

// 事件处理函数
const refreshMeters = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    message.success('表计数据刷新完成');
  }, 1000);
};

const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

const handleReset = () => {
  Object.assign(searchForm, {
    roomNumber: '',
    type: '',
    status: '',
    floor: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

const handleSaveMeter = async () => {
  try {
    await meterFormRef.value.validate();
    if (isEdit.value) {
      message.success('表计信息更新成功');
    } else {
      message.success('表计添加成功');
    }
    showAddMeterModal.value = false;
    resetMeterForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleCancelMeter = () => {
  showAddMeterModal.value = false;
  resetMeterForm();
};

const viewMeter = (record: any) => {
  message.info(
    `查看表计详情: ${record.roomNumber} ${getTypeText(record.type)}`,
  );
};

const viewHistory = (record: any) => {
  message.info(
    `查看历史记录: ${record.roomNumber} ${getTypeText(record.type)}`,
  );
};

const calculateCost = (record: any) => {
  message.info(`计算费用: ${record.roomNumber} ${getTypeText(record.type)}`);
};

const editMeter = (record: any) => {
  isEdit.value = true;
  Object.assign(meterForm, record);
  showAddMeterModal.value = true;
};

const handleAlert = (alert: any) => {
  message.success(`告警"${alert.title}"已处理`);
};

const resetMeterForm = () => {
  Object.assign(meterForm, {
    roomNumber: '',
    type: '',
    model: '',
    manufacturer: '',
    initialReading: '',
    status: 'online',
    ipAddress: '',
    port: '',
    remarks: '',
  });
  isEdit.value = false;
};

onMounted(() => {
  // 初始化数据
  pagination.total = meters.value.length;
});
</script>

<style scoped>
.meters-monitoring {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.monitoring-panel {
  margin-bottom: 24px;
}

.water-monitoring,
.electric-monitoring {
  height: 300px;
}

.monitoring-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.usage-summary {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.usage-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

.usage-label {
  font-size: 12px;
  color: #666;
}

.usage-value {
  font-size: 18px;
  font-weight: 600;
  color: #1890ff;
}

.usage-chart {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  color: #999;
  text-align: center;
}

.chart-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.meters-list-card {
  margin-bottom: 24px;
}

.list-header {
  margin-bottom: 16px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.room-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.room-number {
  font-weight: 500;
  color: #1890ff;
}

.room-type {
  font-size: 12px;
  color: #999;
}

.reading-info,
.usage-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.reading-value,
.usage-value {
  font-weight: 500;
  color: #1890ff;
}

.reading-unit,
.usage-unit {
  font-size: 12px;
  color: #999;
}

.cost-info {
  display: flex;
  align-items: center;
}

.cost-value {
  font-weight: 500;
  color: #f5222d;
}

.update-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.update-time {
  font-size: 12px;
  color: #666;
}

.update-status {
  font-size: 12px;
  font-weight: 500;
}

.update-status.online {
  color: #52c41a;
}

.update-status.offline {
  color: #f5222d;
}

.update-status.abnormal {
  color: #faad14;
}

.alerts-card {
  margin-bottom: 16px;
}

.alerts-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.alert-item {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  padding: 12px;
  border-radius: 6px;
}

.alert-item.critical {
  background-color: #fff2f0;
  border: 1px solid #ffccc7;
}

.alert-item.warning {
  background-color: #fffbe6;
  border: 1px solid #ffe58f;
}

.alert-item.info {
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
}

.alert-icon {
  margin-top: 2px;
  font-size: 16px;
}

.alert-item.critical .alert-icon {
  color: #f5222d;
}

.alert-item.warning .alert-icon {
  color: #faad14;
}

.alert-item.info .alert-icon {
  color: #52c41a;
}

.alert-content {
  flex: 1;
}

.alert-title {
  margin-bottom: 4px;
  font-weight: 500;
}

.alert-desc {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.alert-time {
  font-size: 12px;
  color: #999;
}

.alert-actions {
  display: flex;
  align-items: center;
}

:deep(.ant-card-body) {
  padding: 12px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}
</style>
